package com.nomorerack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.dao.DBUtil;
import com.dao.DealBean;
import com.util.CategoryMapping;

public class NomoreRackHtmlParser {
	
	public  void parserNomoreRack(String url) throws Exception{
		
		DealBean nomorerackBean = new DealBean();
		
		nomorerackBean.setBuy_url(url);
		
        String souceSite = "NomoreRack";
        
        nomorerackBean.setSouce_site(souceSite);
        
        String brand = "";
        
        nomorerackBean.setBrand(brand);
        
        String item = "";
        
        nomorerackBean.setCategory2(item);
		
		Parser parser;
		
		String skuId = "";
		
		try {
			
			parser = new Parser(url);
			
			parser.setEncoding("UTF-8");
			
			NodeFilter skuIdNodeFilter = new AndFilter(new TagNameFilter("input"),new HasAttributeFilter("id", "add_item_daily_deal_item_id"));
            
            NodeList skuIdNodeList = parser.extractAllNodesThatMatch(skuIdNodeFilter); 
            
            if (skuIdNodeList != null && skuIdNodeList.size() > 0) {  

                Tag skuIdNode = (InputTag)skuIdNodeList.elementAt(0);  
                
                skuId = skuIdNode.getAttribute("value");

                nomorerackBean.setSku_id(skuId);

            }
            
            parser.reset();
            
            NodeFilter imageUrlFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "main"));
			 
			 NodeList imageUrlList = parser.extractAllNodesThatMatch(imageUrlFilter);
			             
			    if (imageUrlList != null && imageUrlList.size() > 0) { 
			             	
			    Parser imageparser = new Parser(imageUrlList.toHtml());
			             	
			    NodeFilter imageUrlNodeFilter = new TagNameFilter("img");
			             	
			    NodeList imageUrlNodeList = imageparser.extractAllNodesThatMatch(imageUrlNodeFilter);
			             	
			        if (imageUrlNodeList != null && imageUrlNodeList.size() > 0) { 
			 
			             ImageTag imageUrlNode = (ImageTag) imageUrlNodeList.elementAt(0);
			                 
			             String imageUrl = imageUrlNode.getImageURL();
			                 
			             nomorerackBean.setImage_url(imageUrl);
			             
			             }
			        
			  }
            
            parser.reset();
            
			    NodeFilter contentFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "right"));
		           
		           NodeList contentList = parser.extractAllNodesThatMatch(contentFilter);
		            
		             if (contentList != null && contentList.size() > 0) {  

		            	Parser contentparser = new Parser(contentList.toHtml());
			             	
		 			    NodeFilter productNameNodeFilter = new TagNameFilter("h2");
		 			             	
		 			    NodeList productNameNodeList = contentparser.extractAllNodesThatMatch(productNameNodeFilter);
		 			             	
		 			        if (productNameNodeList != null && productNameNodeList.size() > 0) { 
		 			 
		 			             Node productNameNode = productNameNodeList.elementAt(0);
		 			                 
		 			             String productName = productNameNode.toPlainTextString().trim();
		 			                 
		 			            nomorerackBean.setProduct_name(productName);
		 			                 
		 			             }
		 			    contentparser.reset();
		 			    
		 			    NodeFilter categoryFilter = new TagNameFilter("h5");
		             	
					    NodeList categoryList = contentparser.extractAllNodesThatMatch(categoryFilter);
					             	
					        if (categoryList != null && categoryList.size() > 0) { 
					 
					             Node categoryNode = categoryList.elementAt(0);
					                 
					             String category = categoryNode.toPlainTextString().trim();
					             
					             String category1 = CategoryMapping.getType1(category);
					                 
					             nomorerackBean.setCategory1(category1);
					             System.out.println("@@"+category);
					                 
					             }
					        
					     contentparser.reset();
			 			    
				 	     NodeFilter salePriceFilter = new TagNameFilter("span");
				             	
					     NodeList salePriceList = contentparser.extractAllNodesThatMatch(salePriceFilter);
							             	
							if (salePriceList != null && salePriceList.size() > 0) { 
							 
							      Node salePriceNode = salePriceList.elementAt(0);
							                 
							      String salePrice = salePriceNode.toPlainTextString().trim();
							                 
							      nomorerackBean.setSale_price(salePrice);
							                 
							       }
						 contentparser.reset();
					 			    
						 NodeFilter originalPriceFilter = new TagNameFilter("p");
						             	
						 NodeList originalPriceNodeList = contentparser.extractAllNodesThatMatch(originalPriceFilter);
									             	
							  if (originalPriceNodeList != null && originalPriceNodeList.size() > 0) { 
									 
								   Node originalPriceNode = originalPriceNodeList.elementAt(0);
									                 
								   String originalPrice = originalPriceNode.toPlainTextString().trim();
									             
								   String[] originalPriceList = originalPrice.split(" ");
									                 
								   nomorerackBean.setOriginal_price(originalPriceList[0]);
									                 
								  }

		             } 
		             
		             parser.reset();
		             
		             NodeFilter modelIdNodeFilter = new AndFilter(new TagNameFilter("input"),new HasAttributeFilter("id", "add_item_product_id"));
		             
		             NodeList modelIdNodeList = parser.extractAllNodesThatMatch(modelIdNodeFilter); 
		             
		             if (modelIdNodeList != null && modelIdNodeList.size() > 0) {  

		                 Tag modelIdNode = (InputTag)modelIdNodeList.elementAt(0);  
		                 
		                 String modelId = modelIdNode.getAttribute("value");

		                 nomorerackBean.setModel_id(modelId);

		             }
		             
		             parser.reset();
		             
		             NodeFilter productDescriptionFilter = new AndFilter(new TagNameFilter("p"),new HasAttributeFilter("class", "description"));
		             
		             NodeList productDescriptionList = parser.extractAllNodesThatMatch(productDescriptionFilter);
		              
		               if (productDescriptionList != null && productDescriptionList.size() > 0) { 
		             	
		             	    Node productDescriptionNode = productDescriptionList.elementAt(0);
		                 	
		                 	String productDescription = productDescriptionNode.toPlainTextString().trim();
		                 	
		                 	nomorerackBean.setProduct_description(productDescription);

		               }
		               
		               parser.reset();
			             
		               NodeFilter endsTimeListFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "timeleft"));
			             
			             NodeList endsTimeList = parser.extractAllNodesThatMatch(endsTimeListFilter);
			              
			               if (endsTimeList != null && endsTimeList.size() > 0) { 
			            	   
			            	   Parser endsTimeNodeparser = new Parser(endsTimeList.toHtml());
			            	   
			            	   NodeFilter endsTimeNodeFilter = new TagNameFilter("span");
			            	   
			            	   NodeList endsTimeNodeList = endsTimeNodeparser.extractAllNodesThatMatch(endsTimeNodeFilter);
			            	   
			            	   if(endsTimeNodeList.elementAt(1) != null){
			  	             	
			  	             	    Node endsTimeNode = endsTimeNodeList.elementAt(1);
			  	                 	
			  	                 	String endsTime = endsTimeNode.toPlainTextString().trim();
			  	                 	
			  	                 	nomorerackBean.setEnds_time(endsTime);
			  	                 	
			  	                  System.out.println("@@"+endsTime);
			            	   }else{
			            		   
			            		   nomorerackBean.setEnds_time("");
			            	   }
			            	   
			            	   
			               } 
              
		} catch (ParserException e) {
			
			e.printStackTrace();
		}  
        
		 DBUtil db = new DBUtil();
         
         if(nomorerackBean.getSku_id()!=null){
         
         db.save(nomorerackBean);
         
         }
		
	}
	
	 private static void saveFile(String imgString, String productId) throws Exception {
		  	URL url;
		  	File outFile;
		  	OutputStream os = null;
		  	InputStream is = null;
				try {
					url = new URL(imgString);
					outFile = new File("C:/nordstrom/img/"+productId+".jpg");
					os = new FileOutputStream(outFile);
					is = url.openStream();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] buff = new byte[1024];
				while(true) {
					int readed = is.read(buff);
					if(readed == -1) {
						break;
					}
					byte[] temp = new byte[readed];
					System.arraycopy(buff, 0, temp, 0, readed);
					os.write(temp);
				}
				is.close(); 
		      os.close();
			}

}
